<?php

class Page implements IPage {

	protected $blocks = array();
	protected $main;
	private $data = array();

	public function __construct($name){

		$this->main = Page_Main::Get($name, $this);

		$this->blocks = Page_Block::Get(array($this->main->rid()), array('parent' => $this));


	}

	// Data Functions

	public function data_all(){
		return $this->data;
	}

	public function data_set($data){
		$this->data = $data;
	}

	public function data_top(){
		return isset($this->data[0]) ? $this->data[0] : null;
	}

	public function data_shift(){
		array_shift($this->data);
	}

	// Core Functions

	public function URL($array, $child){
		$url = implode('/', $array);
		return CMS::getInstance()->URL(Page_Rewrite::Unwrite($url));
	}

	public function run(){
		$this->main->run();
		foreach($this->blocks as $block){
			$block->run();
		}
	}

	public function output(){
		try {
	                $template = Output::getInstance()->Template(array('page'));
        	       	$template->main = $this->main->output();
			foreach($this->blocks as $block){
				$block->output();
			}
        	        return $template;
		} catch (Exception $e){ print_r($e); }
	}

	// 

	public static function Load_Page(){
		$site = Site::getInstance();
		$name = isset($_GET['page']) ? $_GET['page'] : $site->getValue('page_home');

		try {
			return new Page($name);
		} catch (Exception $e){
			return new Page_Error($e);
		}
	}
}
